<template>
  <div class="users">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="inget-with-select"
            v-model.trim="pageObj.query"
            clearable
            @clear="getSearch"
            @blur="getSearch"
            @keydown.native.enter="getSearch"
          >
            <el-button
              @click="getSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="usersList"
        max-height="600px"
        border
        style="width: 100%; margin: 10px 0"
      >
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="showEditForm(scope.row)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
            ></el-button>
            <el-button
              @click="delUsers(scope.row)"
              size="mini"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
            <el-button
              @click="showGrantForm(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-s-tools"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageObj.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          prop="username"
          label="用户名"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item
          prop="password"
          label="密码"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机号"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsersForm('form')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 编辑用户 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form ref="editForm" :model="editForm" :rules="rules">
        <el-form-item
          prop="username"
          label="用户名"
          :label-width="formLabelWidth"
        >
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机号"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsersForm('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantForm">
        <el-form-item>
          <p>当前用户：{{ grantForm.username }}</p>
          <p>当前角色：{{ grantForm.role_name }}</p>
        </el-form-item>
        <el-form-item label="重新分配角色" :label-width="formLabelWidth">
          <el-select v-model="roleId" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGrantForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsers,
  getChangeUserState,
  getAddUsers,
  getEditUsers,
  getDelUsers,
  getRoles,
  getGrantRoles
} from "@/api/index";
export default {
  data() {
    var validateMobile = (rule, value, callback) => {
      let regMobile = /^[1]([3-9])[0-9]{9}$/;
      if (!regMobile.test(value)) return callback(new Error("手机号码不规范"));
      callback();
    };
    return {
      usersList: [
        {
          id: 25,
          username: "tige117",
          mobile: "18616358651",
          type: 1,
          email: "tige112@163.com",
          create_time: "2017-11-09T20:36:26.000Z",
          mg_state: true, // 当前用户的状态
          role_name: "炒鸡管理员",
        },
      ],
      total: 0,
      pageObj: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      grantDialogFormVisible: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {
        username: "",
        email: "",
        mobile: "",
        id: 0,
      },
      roleList: [],
      roleId: '',
      grantForm: {},
      formLabelWidth: "120px",
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },
    };
  },
  created() {
    this.getUsersData();
  },
  methods: {
    // 分配角色
    async editGrantForm(){
      if(!this.roleId) return this.$message.warning('请选择所要分配的角色');
      let {meta:{msg,status}}=await getGrantRoles({id:this.grantForm.id,rid:this.roleId})
      if(status!=200) return this.$message.error(msg);
      this.$message.success(msg)
      this.getUsersData();
      this.roleId='';
      this.grantDialogFormVisible = false;
    },
    // 显示分配角色列表框
    async showGrantForm(form) {
      this.grantForm = form;
      let { data ,meta:{msg,status}} = await getRoles();
      if(status!=200) return this.$message.warning(msg);
      this.roleList = data.map(item=> {return {id:item.id,roleName:item.roleName}});
      this.grantDialogFormVisible = true;
    },
    // 删除用户
    async delUsers({ id }) {
      let res = await this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (!res) return this.$message("取消删除");
      let {
        meta: { msg, status },
      } = await getDelUsers(id);
      status == 200 ? this.$message.success(msg) : this.$message.error(msg);
      this.getUsersData();
    },
    // 编辑用户
    async editUsersForm() {
      let {
        meta: { msg, status },
      } = await getEditUsers(this.editForm);
      status == 200?this.$message.success(msg):this.$message.error(msg);
      this.editDialogFormVisible = false;
      this.getUsersData();
    },
    // 显示编辑用户框
    showEditForm({ id, username, email, mobile }) {
      this.editDialogFormVisible = true;
      this.editForm.id = id;
      this.editForm.username = username;
      this.editForm.email = email;
      this.editForm.mobile = mobile;
    },
    // 添加用户
    async addUsersForm(form) {
      try {
        let success = await this.$refs[form].validate();
        if (!success) return false;
        let {
          meta: { msg, status },
        } = await getAddUsers(this.form);
        if (status != 201) return this.$message.error(msg);
        this.$message.success(msg);
        this.addDialogFormVisible = false;
        this.getUsersData();
        for (let item in this.form) {
          this.form[item]=""
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 改变用户状态
    async changeUserState(data) {
      let {
        meta: { msg, status },
      } = await getChangeUserState(data);
      if (status != 200) return this.$message(msg);
      this.$message.success(msg);
      this.getUsersData();
    },
    // 搜索
    getSearch() {
      this.getUsersData();
    },
    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageObj.pagesize = val;
      this.getUsersData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageObj.pagenum = val;
      this.getUsersData();
    },
    // 请求数据
    async getUsersData() {
      let {
        data: { users, total, pagenum },
        meta: {msg,status},
      } = await getUsers(this.pageObj);
      if(status != 200) return this.$message.error(msg);
      this.usersList = users;
      this.pageObj.pagenum =+ pagenum;
      this.total = total;
    },
  },
  components: {},
};
</script>
<style lang="less" scoped>

</style>